package com.hmdp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    private static final String CACHE_SHOP_TYPE = "cache:shop:type";
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Result queryListShopType() {
        //1,查询缓存
        List<String> shopList = stringRedisTemplate.opsForList().range(CACHE_SHOP_TYPE, 0, -1);
        if(CollUtil.isNotEmpty(shopList)){
            List<ShopType> shopTypes = new ArrayList<>();
            for (String shop : shopList){
                ShopType shopType = JSONUtil.toBean(shop, ShopType.class);
                shopTypes.add(shopType);
            }//2,存在则返回
            return Result.ok(shopTypes);
        }
        //3,不存在则查询数据库
        List<ShopType> shopTypes = query().orderByAsc("sort").list();

        //4,为空则报错
        if(CollUtil.isEmpty(shopTypes)){
            return Result.fail("没有查询到数据");
        }
        //5,不为空则写入缓存
        List<String> shopListCache = new ArrayList<>();
        for (ShopType shopType : shopTypes){
            shopListCache.add(JSONUtil.toJsonStr(shopType));
        }
        stringRedisTemplate.opsForList().leftPushAll(CACHE_SHOP_TYPE,shopListCache);
        //6,设置有效期
        stringRedisTemplate.expire(CACHE_SHOP_TYPE, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //6,返回
        return Result.ok(shopTypes);
    }


}
